package models

import (
	"github.com/jinzhu/gorm"
	"kop/libs/database"
	"kop/modules/port/entity"
)

func AutoMigrate() {

	database.DB.AutoMigrate(new(entity.Port))
	database.DB.AutoMigrate(new(entity.PortReport))
}

func GetPorts(portIDs []int32, serverID int32) []entity.Port {

	var ports []entity.Port

	if err := database.DB.Where("port_id IN (?) AND server_id = ? ", portIDs, serverID).Find(&ports).Error; err != nil {
		panic(err)
	}

	return ports
}

func GetPort(portID, serverID int32) *entity.Port {

	var port = &entity.Port{}

	if err := database.DB.Where("port_id = ? AND server_id = ?", portID, serverID).First(port).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		} else {
			panic(err)
		}
	}

	return port
}

func GetPortsByRoleID(roleID int32) []entity.Port {

	var ports []entity.Port

	if err := database.DB.Where("role_id = ? ", roleID).Find(&ports).Error; err != nil {
		panic(err)
	}

	return ports
}

func Save(port *entity.Port) error {

	return database.DB.Save(port).Error
}

func Delete(port *entity.Port) error {

	return database.DB.Delete(port).Error
}

func Create(port *entity.Port) error {

	return database.DB.Create(port).Error
}
